TransportEventBusService.publish   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
1
import { EventBus, EventHandlerType, IEvent, IEventBus, IEventHandler, IEventPublisher } from '@nestjs/cqrs';
2
import { Injectable, Type } from '@nestjs/common';
3
import { ModuleRef } from '@nestjs/core';
4
import { Transport } from '@nestjs/microservices';
5
import { EVENT_NAME, EXCLUDE_DEF, TRANSPORT, TRANSPORTS } from './constants/transport.event-bus.constants';
6
7
@Injectable()
8
export class TransportEventBusService implements IEventBus {
9
    constructor(
10
        readonly publishers: any[],
11
        readonly eventBus: EventBus,
12
        private readonly moduleRef: ModuleRef
13
    ) {
14
    }
15
16
    get publisher(): IEventPublisher {
17
        return this.eventBus.publisher;
18
    }
19
20
    onModuleDestroy(): void {
21
        this.eventBus.onModuleDestroy();
22
    }
23
24
    bind(handler: IEventHandler<IEvent>, name: string): void {
25
        this.eventBus.bind(handler, name);
26
    }
27
28
    registerSagas(types?: Array<Type<any>>): void {
29
        this.eventBus.registerSagas(types);
30
    }
31
32
    register(handlers?: EventHandlerType[]): void {
33
        this.eventBus.register(handlers);
34
    }
35
36
    publish<T extends IEvent>(event: T): void {
37
        this.publishViaPublisher(event);
38
    }
39
40
    publishAll<T extends IEvent>(events: T[]): void {
41
        events.forEach((event: T) => {
42
            this.publishViaPublisher(event);
43
        });
44
    }
45
46
    private publishViaPublisher<T extends IEvent>(event: T): void {
47
        const transports: Transport[] = event[TRANSPORTS] ? event[TRANSPORTS] : [];// tslint:disable-line
48
        const isExcludedDef: boolean = !!event[EXCLUDE_DEF] || false;// tslint:disable-line
49
50
        delete event[TRANSPORTS];// tslint:disable-line
51
        delete event[EXCLUDE_DEF];// tslint:disable-line
52
53
        for (const publisher of this.publishers) {
54
55
            const pub = this.moduleRef.get<IEventPublisher>(publisher);
56
57
            if (transports.includes(pub[TRANSPORT])) {// tslint:disable-line
58
                pub.publish(event);
59
            }
60
        }
61
62
        if (!isExcludedDef) {
63
            delete event[EVENT_NAME];// tslint:disable-line
64
            this.eventBus.publish(event);
65
        }
66
    }
67
}
68